package com.seafwg.web;

import com.seafwg.listener.WebApplicationContextUtils;
import com.seafwg.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author seafwg
 * @Date 2022/2/13 4:18 下午
 * @Version 1.0
 * @description xxx
 */

public class UserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // ----
        // ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        // UserService userService = app.getBean(UserService.class);
        // userService.save();

        // ---- 通过ServletContextListener监听器创建应用，并保存在servlet域中
        // ServletContext servletContext = req.getServletContext();
        // ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app");
        // UserService userService = app.getBean(UserService.class);

        // ---- 优化后通过WebApplicationContextUtils静态方法获取实例
        ServletContext servletContext = this.getServletContext();
        ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        UserService userService = app.getBean(UserService.class);
        userService.save();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // super.doPost(req, resp);

    }
}
